<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			.error{
				color: red;
			}
			.success{
				color: green;
			}
		</style>
	</head>
	<body>
		<script>
			document.addEventListener('DOMContentLoaded', function() {  
				// 通过id获取dom元素
				var usernameInput = document.getElementById('username');  
				console.log(usernameInput)
				var usernameError = document.getElementById('usernameError');  
				var usernameSuccess = document.getElementById('usernameSuccess');  
				var passwordInput = document.getElementById('password');  
				var passwordError = document.getElementById('passwordError');  
				var passwordSuccess = document.getElementById('passwordSuccess');  	
				
				usernameInput.addEventListener('input',function(){
					let username = usernameInput.value
					if(/\s|[^a-zA-Z0-9]/.test(username)){
						usernameError.textContent='用户名不能包含空格或特殊字符'
						usernameError.style.display = 'block';  
						usernameSuccess.style.display = 'none';  
					}else{
						usernameError.style.display = 'none';
						usernameSuccess.textContent='用户名有效'
						usernameSuccess.style.display = 'block';  
					}
				})
				
				passwordInput.addEventListener('input',function(){
					let password = passwordInput.value
					if(password.length<8){
						passwordError.textContent='密码长度至少为8个字符'
						passwordError.style.display = 'block';  
						passwordSuccess.style.display = 'none';
					}else{
						passwordError.style.display = 'none';
						passwordSuccess.textContent='密码有效'
						passwordSuccess.style.display = 'block';  
					}
				})
			})
			
		</script>
		<form action="#">
			<label for="username">用户名</label><input id='username' name="username"/>
			<p id="usernameError" class="error"></p>  
			<p id="usernameSuccess" class="success"></p>
			
			<label for="password">密码</label><input id="password" name="password"/>
			<p id="passwordError" class="error"></p>
			<p id="passwordSuccess" class="success"></p>
			
			<input type="submit" value="提交" />
		</form>
		
	</body>
</html>